package crow.ui;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;

import com.google.gson.Gson;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.SpeechUtility;
import com.iflytek.cloud.SynthesizerListener;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;

import org.apache.http.Header;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import crow.data.WeatherDataProvider;
import crow.utils.DateUtil;
import crow.data.WeatherData;
import crow.data.WeatherInfo;
import crow.receiver.AlarmReceiver;

public class MainActivity extends Activity {
    public static final String MUSIC_STOP_ACTION = "su.crow.MUSIC_STOP";
    public static final String SP_ALARM_RECORD = "alarm_record";
    public static final String SP_ALARM_RECORD_TIME = "alarm_time";
    public static final String ALARM_RECEIVER = "su.crow.ALARM_RECEIVER";

    private TextView mTTSButton;
    private TextView mWeatherButton;
    private TextView mSetAlarmButton;
    private TextView mCancelAlarmButton;
    private SpeechSynthesizer mTts;
    private SharedPreferences mSp;
    private Calendar mCalendar;
    private TextView mTvDateTime;

    private boolean isTTSInited = false;
    private MusicStopReceiver mMusicReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_en);

        mSp = getSharedPreferences(SP_ALARM_RECORD, Activity.MODE_PRIVATE);
        mCalendar = Calendar.getInstance();

        initTTS();

        initControls();

        registerBroadcastReceiver();
    }

    private void initControls() {
        mTvDateTime = (TextView) findViewById(R.id.tv_date_time);
        String time = mSp.getString(SP_ALARM_RECORD_TIME, null);
        if(time == null) {
            mTvDateTime.setText("闹钟取消");
        }else{
            mTvDateTime.setText("当前时间：" + time);
        }

        mTTSButton = (TextView) findViewById(R.id.tv_speech);
        mTTSButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int code = mTts.startSpeaking("Hello 起床了 起床了 快点哦！", mSynListener);
                Log.d("Synthesiezer start code:", code + "");
            }
        });

        mWeatherButton = (TextView) findViewById(R.id.tv_weather);
        mWeatherButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                speechWeather();
            }
        });

        mSetAlarmButton = (TextView) findViewById(R.id.tv_set_alarm);
        mSetAlarmButton.setOnClickListener(new Button.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                mCalendar.setTimeInMillis(System.currentTimeMillis());
                int hour = mCalendar.get(Calendar.HOUR_OF_DAY);
                int minute = mCalendar.get(Calendar.MINUTE);
                new TimePickerDialog(MainActivity.this, minute, new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                        mCalendar.setTimeInMillis(System.currentTimeMillis());
                        mCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
                        mCalendar.set(Calendar.MINUTE, minute);
                        mCalendar.set(Calendar.SECOND, 0);
                        mCalendar.set(Calendar.MILLISECOND, 0);

                        setAlarm(hourOfDay, minute);
                    }
                }, hour, minute, true).show();
            }

        });

        mCancelAlarmButton = (TextView) findViewById(R.id.tv_cancel_alarm);
        mCancelAlarmButton.setOnClickListener(new Button.OnClickListener() {

            @Override
            public void onClick(View v) {
                stopAlarm();
                stopService(new Intent("su.crow.MUSIC"));
            }

        });
    }

    private void stopAlarm() {
        Intent intent = new Intent(ALARM_RECEIVER);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
        AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        am.cancel(pendingIntent);
        mSp.edit().putString(SP_ALARM_RECORD_TIME, null).commit();
        mTvDateTime.setText("闹钟取消");
    }

    private void setAlarm(int hourOfDay, int minute) {
        Intent intent = new Intent(this, AlarmReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
        AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        am.cancel(pendingIntent);
        am.setRepeating(AlarmManager.RTC_WAKEUP,
                mCalendar.getTimeInMillis(),
                AlarmManager.INTERVAL_DAY,
                pendingIntent);

        String timeStr = hourOfDay + ":" + minute;
        mTvDateTime.setText("当前设置的闹钟时间：" + timeStr);
        mSp.edit().putString(SP_ALARM_RECORD_TIME, timeStr).commit();
    }

    private void initTTS() {
        if(!isTTSInited) {
             /*
             set app id
             if used in non-main thread, change parameter to
                SpeechConstant.APPID + "=555359db," + SpeechConstant.FORCE_LOGIN + "=true"
            */
            SpeechUtility.createUtility(this, SpeechConstant.APPID + "=555359db," + SpeechConstant.FORCE_LOGIN + "=true");

            // second parameter used for local synthesize
            mTts = SpeechSynthesizer.createSynthesizer(this, myInitListener);

            mTts.setParameter(SpeechConstant.VOICE_NAME, "xiaoyan");
            mTts.setParameter(SpeechConstant.SPEED, "50");
            mTts.setParameter(SpeechConstant.VOLUME, "80"); //range 0~100
            mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_AUTO);

            // if you want save synthesized audio file into SD card. Remember add access SD permission.
            //mTts.setParameter(SpeechConstant.TTS_AUDIO_PATH, "./sdcard/iflytek.pcm");
        }
    }

    private void speechWeather() {
        AsyncHttpClient client = new AsyncHttpClient();
        String url = WeatherDataProvider.URL_BAIDU_APISTORE_WEATHER;
        client.get(url, null, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                if (i == 200) {
                    String content = new String(bytes);
                    Log.d("HTTP content", content);

                    String date2Speech = "";

                    Date now = new Date();
                    SimpleDateFormat fmt = new SimpleDateFormat("今天是yyyy年MM月dd日 " +
                            DateUtil.getWeekOfDate(now) + "现在时间HH时mm分");
                    date2Speech = fmt.format(now);

                    WeatherData wData = new Gson().fromJson(content, WeatherData.class);
                    WeatherInfo wInfo = wData.getRetData();
                    String w2Speech = wInfo.getCity() + " " + wInfo.getWeather() + " 最高气温 " +
                            wInfo.getH_tmp() + "摄氏度 最低气温 " + wInfo.getL_tmp() + "摄氏度";

                    speech(date2Speech + w2Speech);
                } else {
                    Log.d("HTTP status code:", i + "");
                }
            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                Log.d("HTTP request fail", i + "");
                Date now = new Date();
                String date2Speech = "";
                SimpleDateFormat fmt = new SimpleDateFormat("今天是yyyy年MM月dd日 " +
                        DateUtil.getWeekOfDate(now) + "现在时间HH时mm分");
                date2Speech = fmt.format(now);

                String error = date2Speech + "访问天气数据失败！";
                speech(error);
            }
        });
    }

    private void speech(String content) {
        Log.d("Synthesiezer speech:", content);
        int code = mTts.startSpeaking(content, mSynListener);
        Log.d("Synthesiezer start code:", code + "");
    }

    private void registerBroadcastReceiver() {
        mMusicReceiver = new MusicStopReceiver();
        IntentFilter filter = new IntentFilter(MUSIC_STOP_ACTION);
        registerReceiver(mMusicReceiver, filter);
    }

    @Override
    protected void onDestroy(){
        unregisterReceiver(mMusicReceiver);
    }

    SynthesizerListener mSynListener = new SynthesizerListener() {
        @Override
        public void onSpeakBegin() {

        }

        @Override
        public void onBufferProgress(int i, int i2, int i3, String s) {

        }

        @Override
        public void onSpeakPaused() {

        }

        @Override
        public void onSpeakResumed() {

        }

        @Override
        public void onSpeakProgress(int i, int i2, int i3) {

        }

        @Override
        public void onCompleted(SpeechError speechError) {
            if (speechError != null) {
                Log.d("Synthesiezer complete code:", speechError.getErrorCode() + "");
            } else {
                Log.d("Synthesiezer complete code:", "0");
            }
        }

        @Override
        public void onEvent(int i, int i2, int i3, Bundle bundle) {

        }
    };

    private InitListener myInitListener = new InitListener() {
        @Override
        public void onInit(int code) {
            Log.d("mySynthesiezer:", "InitListener init() code = " + code);
        }
    };

    public class MusicStopReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d("MusicStopReceiver", "call onReceive 1 ");

            String action = intent.getAction();

            if (MUSIC_STOP_ACTION.equals(action)) {
                Log.d("MusicStopReceiver", "call onReceive 2");
                speechWeather();
            }
        }
    }
}
